package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.BannedUserCache;
import com.conversationboard.cache.ThreadCache;
import com.conversationboard.cache.UserCache;
import com.conversationboard.cache.VoterCache;
import com.conversationboard.cache.adminlog.AdminLogCache;
import com.conversationboard.cache.banvote.BanVoteCache;
import com.conversationboard.cache.newanswers.INewAnswersCache;
import com.conversationboard.cache.newanswers.NewAnswersCaches;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;

@WebServlet(name = "AdminClearCachesControllerServlet", urlPatterns = "/Admin/AdminClearCachesControllerServlet")
public class AdminClearCachesControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -2302589291467494243L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			/* New Answers Cache */

			if (request.getParameter("newanswers") != null) {
				int boardId = Integer.parseInt(request.getParameter("boardid"));

				INewAnswersCache cache = NewAnswersCaches.getInstance(boardId);
				cache.clear();
			}

			/* All New Answers Caches */

			if (request.getParameter("allnewanswers") != null) {

				for (Board board : Boards.getAllBoards()) {

					synchronized (NewAnswersCaches.class) {

						INewAnswersCache cache = NewAnswersCaches.getInstance(board.getBoardId());
						cache.clear();
					}
				}

				Site.initialiseSiteNewAnswersCache();

			}

			/* Thread Cache */

			if (request.getParameter("thread") != null) {
				ThreadCache.getInstance().clear();
			}

			/* Ban Vote */

			if (request.getParameter("banvote") != null) {
				BanVoteCache.clear();
			}

			/* User Cache */

			if (request.getParameter("user") != null) {
				UserCache.getInstance().clear();
			}

			/* Voter Cache */

			if (request.getParameter("voter") != null) {
				VoterCache.clear();
			}

			/* Board Cache */

			if (request.getParameter("board") != null) {
				Boards.refreshCache();
			}

			/* Admin Log Cache */

			if (request.getParameter("adminlog") != null) {
				AdminLogCache.getInstance().clear();
			}

			/* Banned User Cache */

			if (request.getParameter("banneduser") != null) {
				BannedUserCache.clear();
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
